# movies/views.py
from django.shortcuts import render
from .models import Movie
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def index(request):
    movies = Movie.objects.all().order_by('-rating')

    # 获取搜索查询参数
    search_query = request.GET.get('q', '')
    
    if search_query:
        # 使用Q对象进行多字段模糊搜索
        movies = movies.filter(
            Q(title__icontains=search_query) |
            Q(director__icontains=search_query) |
            Q(actors__icontains=search_query) |
            Q(genre__icontains=search_query) |
            Q(country__icontains=search_query) |
            Q(year__icontains=search_query) |
            Q(quote__icontains=search_query)
        ).order_by('-rating')

    # 分页功能 - 每页显示10条记录
    paginator = Paginator(movies, 12)
    page_number = request.GET.get('page')
    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        # 如果page参数不是整数，返回第一页
        page_obj = paginator.page(1)
    except EmptyPage:
        # 如果页数超出范围，返回最后一页
        page_obj = paginator.page(paginator.num_pages)

    context = {
        'page_obj': page_obj,
        'search_query': search_query,
    }
    return render(request, 'movies/index.html', context)
